package com.yanqu.road.server.manger.activity.recycle;

import com.yanqu.road.dao.impl.activity.ActivityItemRecycleDaoImpl;
import com.yanqu.road.entity.activity.ActivityItemRecycleData;
import com.yanqu.road.pb.bag.BagProto;
import com.yanqu.road.server.TempMgr;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ActivityItemRecycleMgr extends TempMgr {

    private static Map<Integer, ActivityItemRecycleData> recycleDataMap = new ConcurrentHashMap<>();

    /**
     * 设置物品回收时间，回收类型，关联的活动
     *
     * @param itemId
     * @param activityType
     * @param recycleTime
     */
    public static void addRecycleItemData(int itemId, int activityType, long recycleTime) {
        addRecycleItemData(itemId, activityType, 0, recycleTime, new ArrayList<>());
    }

    /**
     * 回收数据初始化
     * @param itemId 道具ID
     * @param activityType 活动类型
     * @param recycleType 自定义类型，拥有执行回收操作（doRecycle）的时候自定义处理
     * @param recycleTime 执行回收时间
     * @param paramList 自定义参数，拥有执行回收操作（doRecycle）的时候自定义处理。
     *                  paramList参数定义:
         *                  tem2Score方法：
             *                  第一个参数：回收的道具ID
             *                  第二个参数：转换的积分ID
             *                  第三个参数：道具配置param字段下标，配置一个道具回收多少积分
             *                  四个参数：活动名称
     */
    public static synchronized void  addRecycleItemData(int itemId, int activityType, int recycleType, long recycleTime, List<String> paramList) {
        ActivityItemRecycleData data = recycleDataMap.get(itemId);
        if (data == null) {
            data = new ActivityItemRecycleData();
            data.setItemId(itemId);
            data.setActivityType(activityType);
            data.setRecycleTime(recycleTime);
            data.setParamList(paramList);
            data.setRecycleType(recycleType);
            data.setInsertOption();
            recycleDataMap.put(itemId, data);
        }

        if (data.getRecycleTime() >= recycleTime) {
            //已经设置的回收时间比较大  就不要去改了
            return;
        }
        //6.0更新 需要同时更新活动类型
        data.setActivityType(activityType);
        data.setRecycleTime(recycleTime);
        data.setRecycleType(recycleType);
        data.setActivityType(activityType);
        data.setParamList(paramList);
        data.setNeedRecycle(true);
    }

    public static void checkAndAddNeedRecycleItem() {
        List<AbstractItemRecycleStrategy> itemRecycleStrategyList = ItemRecycleStrategyFactory.getItemRecycleStrategyList();
        for (AbstractItemRecycleStrategy recycleStrategy : itemRecycleStrategyList) {
            try {
                recycleStrategy.markNeedRecycleItem();
            } catch (Exception e) {
                getLogger().error("{}  mark recycle item error.",recycleStrategy.getClass().getSimpleName(),e);
            }
        }
    }

    public static void timerRecycle() {
        List<AbstractItemRecycleStrategy> itemRecycleStrategyList = ItemRecycleStrategyFactory.getItemRecycleStrategyList();
        for (AbstractItemRecycleStrategy recycleStrategy : itemRecycleStrategyList) {
           /* if (recycleStrategy.isActivityRunning()) {
                continue;
            }*/
            try {
                recycleStrategy.recycleItem();
            } catch (Exception e) {
                getLogger().error("{}  recycle item error",recycleStrategy.getClass().getSimpleName(),e);
            }
        }
    }

    public static Map<Integer, List<ActivityItemRecycleData>> getNeedRecycleItemByActivityType(int activityType) {
        long now = System.currentTimeMillis();
        Map<Integer, List<ActivityItemRecycleData>> dataMap = new HashMap<>();
        for (ActivityItemRecycleData data : recycleDataMap.values()) {
            if (data.getActivityType() != activityType) {
                continue;
            }
            int batchType = 0;
            List<ActivityItemRecycleData> needRecycleList = dataMap.get(batchType);
            if (needRecycleList == null) {
                needRecycleList = new ArrayList<>();
                dataMap.put(batchType, needRecycleList);
            }
            if (now > data.getRecycleTime()) {
                needRecycleList.add(data);
            }
        }
        return dataMap;
    }

    public static void endItemRecycle(ActivityItemRecycleData data) {
        if (data != null) {
            data.setNeedRecycle(false);
        }
    }

    public static BagProto.RecycleDetailSyncMsg.Builder getRecycleDetail(){
        BagProto.RecycleDetailSyncMsg.Builder builder =BagProto.RecycleDetailSyncMsg.newBuilder();
        for (ActivityItemRecycleData activityItemRecycleData:recycleDataMap.values()){
            BagProto.RecycleDetail.Builder detailBuilder =  BagProto.RecycleDetail.newBuilder();
            detailBuilder.setActivityType(activityItemRecycleData.getActivityType());
            detailBuilder.setItemId(activityItemRecycleData.getItemId());
            detailBuilder.setTime(activityItemRecycleData.getRecycleTime());
            builder.addRecycle(detailBuilder);
        }
        return builder;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        recycleDataMap = new ActivityItemRecycleDaoImpl().getActivityItemRecycleData();
        return true;
    }

    @Override
    public boolean save() {
        for (ActivityItemRecycleData data : new ArrayList<>(recycleDataMap.values())) {
            if (data.isInsertOption()) {
                new ActivityItemRecycleDaoImpl().add(data);
            } else if (data.isUpdateOption()) {
                new ActivityItemRecycleDaoImpl().update(data);
            }
        }
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    /**
     * 测试用的,没判断时间的
     *
     * @param activityType
     * @return
     */
    public static List<ActivityItemRecycleData> testGetNeedRecycleItemByActivityType(int activityType) {
        List<ActivityItemRecycleData> needRecycleList = new ArrayList<>();
        Map<Integer, List<ActivityItemRecycleData>> dataMap = new HashMap<>();
        for (ActivityItemRecycleData data : recycleDataMap.values()) {
            if (data.getActivityType() != activityType) {
                continue;
            }
            needRecycleList.add(data);
        }
        return needRecycleList;
    }
}
